package com.gitee.baqkft.code.ui.dlg;

import com.gitee.baqkft.code.ui.layout.GBC;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;

/**
 * image转base64工具
 * @Author: chenmingcai
 * @Date 2020/6/23 4:22 下午
 **/

public class ImageBase64Frame extends JFrame
{
    /**
     * 图片
     */
    private JTextField imageField;

    /**
     * 文件区域
     */
    private JTextArea textArea;

    public ImageBase64Frame()
    {
        setLayout(new GridBagLayout());
        setSize(600, 400);

        JPanel browsPanel = createBrowsePanel();
        GBC gbc = new GBC(0, 0, 1, 1);
        gbc.setWeight(1, 0).setFill(GBC.HORIZONTAL);
        browsPanel.setBorder(BorderFactory.createTitledBorder("图片文件"));
        add(browsPanel, gbc);

        textArea = new JTextArea();
        gbc = new GBC(0, 1, 1, 1);
        gbc.setWeight(1, 1).setFill(GBC.BOTH);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        add(new JScrollPane(textArea), gbc);
    }

    /**
     * 创建图片文件选择组件
     * @return
     */
    private JPanel createBrowsePanel()
    {
        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());

        JLabel label = new JLabel("选择图片:");
        GBC gbc = new GBC(0, 0, 1, 1);
        gbc.setWeight(0, 0);
        panel.add(label, gbc);

        imageField = new JTextField();
        gbc = new GBC(1, 0, 1, 1);
        gbc.setWeight(1, 0).setFill(GBC.HORIZONTAL);
        panel.add(imageField, gbc);

        JButton browse = new JButton("选择");
        gbc = new GBC(2, 0, 1, 1);
        gbc.setWeight(0, 0);
        panel.add(browse, gbc);
        browse.addActionListener(this::chooseImageFile);

        return panel;
    }

    /**
     * 选择图片文件
     * @param event
     */
    private void chooseImageFile(ActionEvent event)
    {
        JFileChooser chooser = new JFileChooser();
        File file = new File(imageField.getText().trim());
        if(file.exists())
        {
            chooser = new JFileChooser(imageField.getText());
        }

        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        if(JFileChooser.APPROVE_OPTION == chooser.showDialog(this, "选择"))
        {
            String dir = chooser.getSelectedFile().getPath();
            file = new File(dir);
            if(!file.exists())
            {
                int idx = dir.lastIndexOf(File.separator);
                dir = dir.substring(0, idx);
            }
            imageField.setText(dir);
            try
            {
                textArea.setText(convert(imageField.getText()));
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
    }

    private String convert(BufferedImage image) throws IOException
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", bos);
        StringBuffer buffer = new StringBuffer("data:image/jpeg;base64,");
        buffer.append(Base64.getEncoder().encodeToString(bos.toByteArray()));
        return buffer.toString();
    }

    /**
     * 将本地文件转换成BASE64
     * @param imagePath
     * @return
     * @throws IOException
     */
    private String convert(String imagePath) throws IOException
    {
        InputStream ins = new FileInputStream(imagePath);
        byte[] data = new byte[ins.available()];
        ins.read(data);

        int idx = imagePath.lastIndexOf(".");
        String extName = "jpeg";
        if(idx > 0)
            extName = imagePath.substring(idx + 1);

        StringBuffer buffer = new StringBuffer("data:image/");
        buffer.append(extName).append(";base64,");
        buffer.append(Base64.getEncoder().encodeToString(data));
        return buffer.toString();
    }
}
